package com.qf.cx.simplenms.persist.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.qf.cx.simplenms.persist.dao.api.SubscriberDao;
import com.qf.cx.simplenms.persist.entity.SubscriberEntity;

@Repository
public class SubscriberDaoImpl implements SubscriberDao {
	@Autowired
	@Qualifier("hibernateSessionFactory")
	private SessionFactory sessionFactory;

	@Override
	public void addSubscriber(SubscriberEntity subscriber) {
		Session session = sessionFactory.getCurrentSession();
		session.save(subscriber);
	}

	@Override
	public void deleteSubscriber(long id) {
		Session session = sessionFactory.getCurrentSession();
		SubscriberEntity subscriberEntity = session.get(SubscriberEntity.class, id);
		if (subscriberEntity != null) {
			session.delete(subscriberEntity);
		}
	}

	@Override
	public void updateSubscriber(SubscriberEntity subscriber) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(subscriber);
	}

	@Override
	public SubscriberEntity getSubscriber(long id) {
		Session session = sessionFactory.getCurrentSession();
		SubscriberEntity subscriberEntity = session.get(SubscriberEntity.class, id);
		return subscriberEntity;
	}

	@Override
	public List<SubscriberEntity> getSubscribers() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from SubscriberEntity");
		List<SubscriberEntity> list = query.list();
		return list;
	}

	@Override
	public void addSubscriber(List<SubscriberEntity> subscribers) {
		subscribers.forEach(t -> addSubscriber(t));
	}

}
